#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <errno.h>

typedef void (*func_t)();

#define NUM 5
func_t handlers[NUM];

void registerHandlers(func_t h[], func_t f)
{
    int i = 0;
    for(; i < NUM; i++)
    {
        if(h[i] == NULL) break;
    }
    if(i == NUM) return;
    h[i] = f;
    h[i + 1] = NULL;
}

void downLoad()
{
    printf("这是一个下载任务...\n");
}

void flush()
{
    printf("这是一个刷新任务...\n");
}

void login()
{
    printf("这是一个登录任务...\n");
}

int main()
{
    registerHandlers(handlers, downLoad);
    registerHandlers(handlers, flush);
    registerHandlers(handlers, login);

    pid_t id = fork();
    if(id == 0)
    {
        int count = 5;
        //while(count)
        while(1)
        {
            sleep(3);
            printf("我是一个子进程，pid：%d，ppid：%d\n", getpid(), getppid());
            sleep(1);
            count--;
        }
        int *p = 0;
        *p = 20;
        exit(23);
    }
    while(1)
    {
        int status = 0;
        pid_t rid= waitpid(id, &status, WNOHANG);
        if(rid > 0)
        {
            if(WIFEXITED(status))
                printf("wait success! status: %d, exit_code: %d, signal_code: %d\n", status, WEXITSTATUS(status), status & 0x7f);
            else printf("子进程退出异常\n");
            break;
        }
        else if(rid == 0)
        {
            int i = 0;
            for(; handlers[i]; i++)
            {
                handlers[i]();
            }
            printf("本轮调用结束，子进程没有退出\n");
            sleep(1);
        }
        else printf("%d->%s\n", errno, strerror(errno));
    }

    //pid_t rid = wait(NULL);
    //int status = 0;
    //pid_t rid = waitpid(id, &status, 0);
    //if(rid > 0)
    //{
    //    if(WIFEXITED(status))
    //    {
    //        printf("successfully waited! pid: %d, status: %d, exit_code: %d, signal_code: %d\n", getpid(), status, WEXITSTATUS(status), status&0x7f);
    //
    //    }
    //    else 
    //    {
    //        printf("程序退出异常\n");
    //    }
    //}
    //else 
    //{
    //    printf("%d->%s\n", errno, strerror(errno));
    //}



    //printf("main");
    //sleep(2);
    ////exit(23);
    //_exit(23);




    //for(int i = 0; i < 200; i++)
    //{
    //    printf("%d->%s\n", i, strerror(i));
    //}




    //printf("hello world\n");
    //
    //FILE* pf = fopen("log.txt", "r");
    //if(pf == NULL) return 1;

    ////读取
    //
    //fclose(pf);

    return 0;
}
